import { PerformanceInfo, SDKConfig } from '../types';
import { getPerformanceMetrics, shouldSample } from '../utils';

export class PerformanceMonitor {
  private config: SDKConfig;
  private performanceHandler: (performance: PerformanceInfo) => void;
  private isInitialized = false;

  constructor(config: SDKConfig, performanceHandler: (performance: PerformanceInfo) => void) {
    this.config = config;
    this.performanceHandler = performanceHandler;
  }

  // 初始化性能监控
  public init(): void {
    if (this.isInitialized) {
      return;
    }

    this.isInitialized = true;

    // 监听页面加载完成
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        this.collectPerformanceData();
      });
    } else {
      this.collectPerformanceData();
    }

    // 监听页面完全加载
    window.addEventListener('load', () => {
      this.collectPerformanceData();
    });

    // 监听页面可见性变化
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') {
        this.collectPerformanceData();
      }
    });
  }

  // 收集性能数据
  private collectPerformanceData(): void {
    if (!shouldSample(this.config.sampleRate)) {
      return;
    }

    const metrics = getPerformanceMetrics();
    
    if (metrics.loadTime || metrics.domContentLoadedTime) {
      const performanceInfo: PerformanceInfo = {
        loadTime: metrics.loadTime || 0,
        domContentLoadedTime: metrics.domContentLoadedTime || 0,
        fcp: metrics.fcp,
        lcp: metrics.lcp,
        fid: metrics.fid,
        cls: metrics.cls,
        timestamp: Date.now()
      };

      this.performanceHandler(performanceInfo);
    }
  }

  // 手动上报性能信息
  public reportPerformance(performance: PerformanceInfo): void {
    if (!shouldSample(this.config.sampleRate)) {
      return;
    }

    this.performanceHandler(performance);
  }

  // 获取当前性能指标
  public getCurrentPerformance(): Partial<PerformanceInfo> {
    return getPerformanceMetrics();
  }

  // 销毁性能监控器
  public destroy(): void {
    this.isInitialized = false;
    // 移除事件监听器
    document.removeEventListener('DOMContentLoaded', this.collectPerformanceData);
    window.removeEventListener('load', this.collectPerformanceData);
    document.removeEventListener('visibilitychange', this.collectPerformanceData);
  }
} 